module dgl.graphics.Model;

import std.c.stdio;
import std.file;
import std.stream;
import std.stdio;
import std.string;
import std.conv;

import derelict.opengl.gl;

import dgl.graphics.ModelMesh;
import dgl.graphics.LoadHelper;
import dgl.graphics.MeshContainer;

class Model
{
	private MeshContainer[] m_meshContainers;
	
	public this()
	{
		m_meshContainers = null;
	}
	
	public MeshContainer[] meshContainers()
	{
		return m_meshContainers;
	}

	public static Model loadFromFile( string filename )
	{
		LoadHelper loadHelper = new LoadHelper( filename );
		
		Model ret = new Model();
		
		int meshes = 0;
		string data;
		if( loadHelper.readLine( data ) == "Meshes" )
		{
			meshes = toUint( data );
			ret.m_meshContainers = new MeshContainer[meshes];
			for( int i = 0; i < meshes; i++ )
			{
				ret.m_meshContainers[i] = MeshContainer.loadFromFile( loadHelper, ret );
			}
		}
		
		foreach( meshContainer; ret.m_meshContainers )
		{
			if( meshContainer.parentName is null )
			{
				meshContainer.parent = null;
				break;
			}
			foreach( parentContainer; ret.m_meshContainers )
			{
				if( meshContainer.parentName == parentContainer.name )
				{
					meshContainer.parent = parentContainer;
					break;
				}
			}
		}
		
		foreach( meshContainer; ret.m_meshContainers )
		{
			meshContainer.calculateAbsoluteTransform();
		}
		
		return ret;
	}
}